package cn.cuilan.server.core;

import cn.cuilan.common.core.ProtocolMessageListener;
import cn.cuilan.common.entity.EchoMessage;
import cn.cuilan.common.entity.HttpEntity;
import cn.cuilan.common.entity.ProtocolMessage;
import cn.cuilan.common.utils.HttpHelper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 服务端消息处理类
 *
 * @author zhang.yan
 */
@Slf4j
@Component
public class NetServerMessageProcessor implements ProtocolMessageListener<ProtocolMessage> {

    private HttpHelper httpHelper = new HttpHelper();

    @Override
    public boolean applies(ProtocolMessage protocolMessage) {
        return true;
    }

    @Override
    public boolean onMessage(ChannelHandlerContext ctx, ProtocolMessage protocolMessage) {
        process(ctx, protocolMessage);
        return false;
    }

    public void process(ChannelHandlerContext ctx, ProtocolMessage protocolMessage) {
        // 心跳检测
        if (protocolMessage instanceof EchoMessage) {
            EchoMessage echoMessage = new EchoMessage(EchoMessage.PONG);
            echoMessage.pack();
            ctx.writeAndFlush(echoMessage);
            return;
        }

        HttpEntity requestEntity;
        if (protocolMessage instanceof HttpEntity) {
            requestEntity = (HttpEntity) protocolMessage;
        } else {
            log.info("un support class: {}", protocolMessage.getClass());
            return;
        }
        HttpEntity responseEntity;
        try {
            if ("GET".equals(requestEntity.getMethod())) {
                responseEntity = httpHelper.get(requestEntity.getUrl(), requestEntity.getHeaders());
            } else if ("POST".equals(requestEntity.getMethod())) {
                responseEntity = httpHelper.post(requestEntity.getUrl(),
                        requestEntity.getHeaders(),
                        requestEntity.getFormData());
            } else {
                return;
            }
        } catch (IOException e) {
            log.info(e.getMessage());
            return;
        }
        responseEntity.pack();
        ctx.writeAndFlush(responseEntity);
    }
}
